#include "am2120.h"
#include <Arduino.h>
int readAM2120(float *fhumidity, float *ftemp)
{
    pinMode(AM2120_SDA, OUTPUT);
    digitalWrite(AM2120_SDA, LOW);
    delay(5);
    uint8_t data[5];
    unsigned long time = micros();
    pinMode(AM2120_SDA, INPUT_PULLUP);
    delayMicroseconds(25);
    time = micros();
    while (digitalRead(AM2120_SDA))
    {
        if (micros() - time > 100) // 延时可能不对，需确认
            break;
    }
    time = micros();
    while (!digitalRead(AM2120_SDA)) // 应答低电平
        if (micros() - time > 90)
            return -1;
    time = micros();
    while (digitalRead(AM2120_SDA)) // 应答低电平
        if (micros() - time > 90)
            return -2;
    for (int i = 0; i < 5; i++)
        for (int j = 0; j < 8; j++)
        {
            time = micros();
            while (!digitalRead(AM2120_SDA))
                if (micros() - time > 55)
                    return -3; // timeout waiting for start of data bit.
            delayMicroseconds(40);
            data[i] = (data[i] << 1) + (digitalRead(AM2120_SDA) ? 1 : 0);
            time = micros();
            // Wait for data line to go low
            while (digitalRead(AM2120_SDA))
                if (micros() - time > 55)
                    return -4; // Timeout waiting for end of data bit
        }
    if ((uint8_t)(data[0] + data[1] + data[2] + data[3]) != data[4])
        return -3; // checksum failure.
    uint16_t humidity = ((int)data[0] << 8) + ((int)data[1]);
    uint16_t temp = ((int)data[2] << 8) + ((int)data[3]);
    *fhumidity = (float)(humidity) / 10.0f;
    *ftemp = (float)(temp & 0x7FFF) / 10.0f;
    if (temp & 0x8000)
        *ftemp = -*ftemp;
    digitalWrite(AM2120_SDA, HIGH);
    return 0;
}